<template>
  <div class="uge">
    <Form :model="editData" :rules="ruleValidate" ref="groupEditform" :label-width="100">
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="groupCode" :label="$t('module.general.groupCode')">
            <Input
              type="text"
              class="uge-groupName"
              v-model.trim="editData.groupCode"
              :placeholder="$t('module.general.tip.input')"
              :disabled="!!editData.id"
            />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="groupName" :label="$t('module.general.groupName')">
            <Input type="text" class="uge-groupName" v-model.trim="editData.groupName" :placeholder="$t('module.general.tip.input')"/>
          </Form-item>
        </Col>
      </Row>
      
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="startDate" :label="$t('module.general.startDate')">
            <DatePicker
              style="width: 100%"
              v-model="editData.startDate"
              type="date"
              transfer
              :editable="false"
              :clearable="false"
              :options="startDateOptions"
              @on-change="changeEffectBegin"
            />
          </Form-item>
        </Col>
        <Col span="12">
          <Form-item prop="endDate" :label="$t('module.general.endDate')">
            <DatePicker
              style="width: 100%"
              v-model="editData.endDate"
              transfer
              :editable="false"
              :clearable="false"
              :options="endDateOptions"
              @on-change="changeEffectEnd"
              type="date"
              :placeholder="$t('module.general.tip.selectDate')"
            />
          </Form-item>
        </Col>
      </Row>
      <Row :gutter="32" class="code-row-bg">
        <Col span="12">
          <Form-item prop="enabled" :label="$t('common.status')">
            <RadioGroup v-model="editData.enabled" size="small">
              <Radio label="1">
                <span>{{ $t("common.enable") }}</span>
              </Radio>
              <Radio label="0">
                <span>{{ $t("common.disable") }}</span>
              </Radio>
            </RadioGroup>
          </Form-item>
        </Col>
        <Col span="12">
          <!-- 备注 改为 描述 -->
          <Form-item prop="description" :label="$t('common.describe')">
            <Input v-model="editData.description" type="textarea" :rows="4" :placeholder="$t('module.general.tip.input')" />
          </Form-item>
        </Col>
      </Row>
    </Form>
  </div>
</template>
<script>
import locales from "./locales.js";
import { addUserGroup, findGroupList } from "@/api/userGroupApi";
import { codeReg } from "@/const.js";
// import tenantAPI from "@/api/tenantApi.js";
// 一天的毫秒数
const ONE_DAY = 86400000;
const DefaultEditeData = {
  id: "",
  groupName: "",
  groupCode: "",
  // productId: "",
  tenantId: "",
  startDate: "",
  endDate: "",
  enabled: "1",
  description: ""
};
export default {
  name: "UserGroupEdit",
  mixins: [locales],
  data() {
    const validateGroupCode = (rule, value, callback) => {
      if (!value) {
        callback(new Error(this.$t("module.general.tip.groupCode")));
      } else if (value.length > 30) {
        callback(new Error(this.$t("common.warning.codeCheckLength")));
      } else if (!new RegExp(codeReg).test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else if (new RegExp("[\u4e00-\u9fa5]").test(value)) {
        callback(new Error(this.$t("common.warning.codeCheckCharacter")));
      } else {
        callback();
      }
    };
    return {
      editData: { ...DefaultEditeData },
      ruleValidate: {
        groupName: [
          { required: true, message: this.$t("module.general.tip.roleTip"), trigger: "blur" },
          { min: 1, max: 50, message: this.$t("common.lenthRang.oneToFifty"), trigger: "blur" }
        ],
        groupCode: [{ required: true, validator: validateGroupCode, trigger: "blur" }],
        // startDate: [
        //   { required: true, message: this.$t("module.general.tip.selectDate"), type: "date", trigger: "blur" }
        // ],
        // startDate: [{ required: true, type: "string", trigger: "change" }],
        // endDate: [{ required: true, type: "string", trigger: "change" }],
        // endDate: [{ required: true, message: this.$t("module.general.tip.selectDate"), type: "date", trigger: "blur" }]
        enabled: [{ required: true, message: this.$t("module.general.tip.selectStatus"), trigger: "change" }],
        description: [{ min: 1, max: 255, message: this.$t("common.lenthRang.oneTo255"), trigger: "blur" }]
      }
    };
  },
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  computed: {
    actions() {
      return [
        {
          text: this.$t("common.save"),
          theme: "primary",
          // icon: "edit",
          handle: () => {
            this.save();
          },
          loading: false
        },
        {
          text: this.$t("common.close"),
          // theme: "primary",
          handle: () => this.$emit("Close")
        }
      ];
    },
    startDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.editData.endDate == "object") {
            // 日期是日期对象，如 new Date()
            return (
              date &&
              date.valueOf() < Date.now() - ONE_DAY &&
              date.valueOf() > _this.editData.endDate.valueOf() - ONE_DAY
            );
          } else if (typeof _this.editData.endDate == "string") {
            // 日期是日期字符串，如 2020-01-08
            // 转换日期格式
            let formatStr = _this.editData.endDate.replace(/-/g, "/");
            let endDate = new Date(formatStr);
            return date && (date.valueOf() < Date.now() - ONE_DAY || date.valueOf() > endDate.valueOf());
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    },
    endDateOptions() {
      let _this = arguments[0];
      return {
        disabledDate(date) {
          if (typeof _this.editData.startDate == "object") {
            // 生效日期是日期对象，如 new Date()
            return date && date.valueOf() < _this.editData.startDate.valueOf();
          } else if (typeof _this.editData.startDate == "string") {
            // 生效日期是日期字符串，如 2020-01-08
            // 转换日期格式
            if (_this.editData.startDate == "") {
              return date && date.valueOf() < Date.now() - ONE_DAY;
            }
            let formatStr = _this.editData.startDate.replace(/-/g, "/");
            let startDate = new Date(formatStr);
            return date && date.valueOf() < startDate.valueOf();
          }
          return date && date.valueOf() < Date.now() - ONE_DAY;
        }
      };
    }
  },
  created() {
    // this.initTenant();
    this.$emit("SetTitle", this.$t(`module.general.${this.info.id ? "editGroup" : "addGroup"}`));
    this.$emit("SetPageWidth", 800);
    this.$emit("SetPageActions", this.actions);
    this.initForm();
  },
  mounted() {},
  methods: {
    getNowDate() {
      let date = new Date();
      let seperator1 = "-";
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let strDate = date.getDate();
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
      }
      const currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },
    // 补零
    addZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 格式化时间
    formatDateTime(date) {
      // var time = new Date(Date.parse(date));
      // time.setTime(time.setHours(time.getHours() + 8));
      // var Y = time.getFullYear() + "-";
      // var M = this.addZero(time.getMonth() + 1) + "-";
      // var D = this.addZero(time.getDate()) + " ";
      // var h = this.addZero(time.getHours()) + ":";
      // var m = this.addZero(time.getMinutes()) + ":";
      // var s = this.addZero(time.getSeconds());
      // return Y + M + D;
      // 解决IE不支持Data.parse()的问题
      return date ? new Date(date.replace(/-/g, "/")).Format("yyyy-MM-dd") : "";
    },
    initForm() {
      if (!this.info.id) {
        this.editData.startDate = new Date().toISOString().replace(/T.*/, " ").trim();
        this.editData.endDate = "2099-12-31";
        this.editData.enabled = "1";
      } else {
        this.editData = Object.assign({}, this.info, {
          startDate: this.formatDateTime(this.info.startDate),
          endDate: this.info.endDate == null ? "" : this.formatDateTime(this.info.endDate)
        });
        this.editData.enabled = this.editData.enabled.toString();
      }
    },
    changeEffectBegin(date) {
      this.editData.startDate = date;
    },

    changeEffectEnd(date) {
      this.editData.endDate = date;
    },
    dateToString(dateVal) {
      let date = new Date(dateVal);
      var year = date.getFullYear();
      var month = (date.getMonth() + 1).toString();
      var day = date.getDate().toString();
      if (month.length == 1) {
        month = "0" + month;
      }
      if (day.length == 1) {
        day = "0" + day;
      }
      var hours = date.getHours().toString();
      if (hours.length == 1) {
        hours = "0" + hours;
      }
      var mintus = date.getMinutes().toString();
      if (mintus.length == 1) {
        mintus = "0" + mintus;
      }
      var second = date.getSeconds().toString();
      if (second.length == 1) {
        second = "0" + second;
      }
      var dateTime = year + "-" + month + "-" + day + " " + hours + ":" + mintus + ":" + second;
      return dateTime;
    },
    save() {
      let { groupName, tenantId, startDate, endDate, enabled, groupCode, id, description } = this.editData;
      // const reg = /[\u4E00-\u9FA5]/;
      // if (reg.test(groupCode)) return this.$message.error("用户组编码不能为中文");
      this.$refs["groupEditform"].validate(valid => {
        if (valid) {
          this.actions[0].loading = true;
          startDate = this.dateToString(startDate);
          if (endDate) {
            endDate = this.dateToString(endDate);
          }
          enabled = parseInt(enabled);
          addUserGroup({ groupName, tenantId, startDate, endDate, enabled, groupCode, id, description })
            .then(() => {
              this.$emit("Close", true);
              this.$message.success({
                content: this.$t(`common.${this.info.id ? "updateSuccess" : "saveSuccess"}`),
                duration: 3
              });
            })
            .catch(() => {
              this.actions[0].loading = false;
            });
        } else {
          this.$message.error(this.$t("common.formValidateFailed"));
        }
      });
    }
    // 初始化所属租户
    // initTenant() {
    // if (this.info.id) {
    // tenantAPI.queryAllTenantList().then(data => {
    //   this.tenantList = data;
    // });
    // } else {
    // tenantAPI.queryTenantList().then(data => {
    //   this.tenantList = data;
    // });
    // }
    // }
  },
  watch: {
    info: {
      handler: function (val) {
        // const { currentPost } = this;
        // if (!val.id) {
        //   this.editData = Object.assign({}, DefaultEditeData, {
        //     productId: currentPost.productId,
        //     tenantId: currentPost.tenantCode
        //   });
        //   return;
        // }
        this.editData = Object.assign({}, val);
      },
      immediate: true
    }
  }
};
</script>
<style lang="less">
// .uge {
//   padding: 0 20px;
//   &-groupName input {
//     width: 300px;
//   }
// }
// .ivu-form-item-content {
//   display: inline-block;
// }
</style>
